package com.jiuzhe.commercial.main;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.jiangyy.easydialog.SingleChoiceDialog;
import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseActivity;
import com.jiuzhe.commercial.bean.RegisterBean;
import com.jiuzhe.commercial.bean.ossTokenBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.CustomHelper;
import com.jiuzhe.commercial.utils.UIUtils;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by huanghao on 2018/5/25.
 */

public class RegisterNextActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.iv_pictures)
    ImageView ivPictures;
    @BindView(R.id.ll_pictures)
    LinearLayout llPictures;
    @BindView(R.id.iv_img)
    ImageView ivImg;
    @BindView(R.id.ll_img)
    LinearLayout llImg;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.cb_register)
    CheckBox cbRegister;
    boolean flag = true;
    private File file;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private String idPhotoPersonUrl;
    private String idPhotoUrl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_next_register);
        setTitle("注册");
       // setRringTitle("登录");
        setOnClik();
    }


    private void setOnClik() {
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                UIUtils.startActivity(LoginActivity.class);
            }
        });
    }

    @Override
    protected void loadData() {

    }

    @OnClick({R.id.bt_next,R.id.ll_pictures,R.id.ll_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_next:
                nextRegister();
             //   UIUtils.startActivity(SettingPayPassWordActivity.class);
               break;
            case R.id.ll_pictures:  //拍照
                flag = true;
                new SingleChoiceDialog.Builder(this).setTitle("提示")
                        .addList(new String[]{"拍照上传", "从相册选择照片"})
                        .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                            @Override
                            public void OnItemClick(String title, int position) {
                                CustomHelper customHelper = new CustomHelper(getTakePhoto());
                                file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                                if (!file.getParentFile().exists()) {
                                    file.getParentFile().mkdirs();
                                }
                                Uri imageUri = Uri.fromFile(file);
                                if (position == 0) {
                                    takePhoto.onPickFromCaptureWithCrop(imageUri, customHelper.getCropOptions());
                                }else {
                                    takePhoto.onPickMultiple(1);
                                }
                            }
                        }).show();

                break;
            case R.id.ll_img:  //拍照
                flag = false;
                new SingleChoiceDialog.Builder(this).setTitle("提示")
                        .addList(new String[]{"拍照上传", "从相册选择照片"})
                        .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                            @Override
                            public void OnItemClick(String title, int position) {
                                CustomHelper customHelper2 = new CustomHelper(getTakePhoto());
                                File file1 = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                                if (!file1.getParentFile().exists()) {
                                    file1.getParentFile().mkdirs();
                                }
                                Uri imageUri1 = Uri.fromFile(file1);
                                if (position == 0) {
                                    takePhoto.onPickFromCaptureWithCrop(imageUri1, customHelper2.getCropOptions());
                                }else {
                                    takePhoto.onPickMultiple(1);
                                }
                            }
                        }).show();
                break;
        }
    }

    private void nextRegister() {
        if (ivPictures.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.id_img).getConstantState())) {
            UIUtils.showToastSafe("请上传本人手持身份证正面照片");
            return;
        }
        if (ivImg.getDrawable().getCurrent().getConstantState().equals(getResources().getDrawable(R.mipmap.id_card).getConstantState())) {
            UIUtils.showToastSafe("请上传本人身份证反面照片");
            return;
        }
         if (!cbRegister.isChecked()) {
            UIUtils.showToastSafe("请同意九折用户协议");
            return;
        }
        RegisterBean registerBean = (RegisterBean) getIntent().getSerializableExtra("register");
        registerBean.setIdPhotoPersonUrl(idPhotoPersonUrl);
        registerBean.setIdPhotoUrl(idPhotoUrl);
        Intent intent = new Intent(this,SettingPayPassWordActivity.class);
        intent.putExtra("register",(Serializable)registerBean);
        startActivity(intent);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }



    @Override
    public void takeSuccess(TResult result) {
        if (flag) {
            Glide.with(mContext)
                    .load(new File(result.getImage().getCompressPath()))
                    .into(ivPictures);
            ossToken(result.getImage().getCompressPath());
        } else {
            Glide.with(mContext)
                    .load(result.getImage().getCompressPath())
                    .into(ivImg);
            ossToken(result.getImage().getCompressPath());
        }
    }


    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    /**
     * 上传图片
     *
     * @param path
     */
    private void ossToken(final String path) {
        HashMap<String, String> map = new HashMap<>();
        // map.put("id", "123");
        String url = Constants.OSS_TOKEN + "?id=123";
        HttpClient.get(this, url, map, new CallBack<ossTokenBean>() {
            @Override
            public void onSuccess(ossTokenBean result) {
                upload(path, result.getAccessKeyId(), result.getAccessKeySecret(), result.getSecurityToken());
            }
        });
    }

    private void upload(String path, String accessKeyId, String accessKeySecret, String securityToken) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("jzt-hotel-img", imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                if (flag) {
                    idPhotoPersonUrl = "https://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/" + imgName + ".jpg";
                } else {
                    idPhotoUrl = "https://jzt-hotel-img.oss-cn-hangzhou.aliyuncs.com/" + imgName + ".jpg";
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }
}
